package com.jushu.storbox;

import java.util.HashMap;
import java.util.Map;

import com.jushu.storbox.constant.ReceiverConstent;
import com.jushu.storbox.constant.UiConstant;
import com.jushu.storbox.database.DAOFactory;
import com.jushu.storbox.database.IUserDao;
import com.jushu.storbox.entities.User;
import com.jushu.storbox.manager.AlbumBackManager;
import com.jushu.storbox.manager.AlbumUploadTaskManager;
import com.jushu.storbox.manager.ShareScanManager;
import com.jushu.storbox.newfragment.AbsFrameFragment;
import com.jushu.storbox.newfragment.AlbumBackFragment;
import com.jushu.storbox.newfragment.FileFragment;
import com.jushu.storbox.newfragment.SettingFragment;
import com.jushu.storbox.newfragment.ShareFragment;
import com.jushu.storbox.newfragment.TeamFragment;
import com.jushu.storbox.newfragment.TranslateFragment;
import com.jushu.storbox.newfragment.argument.Arguments;
import com.jushu.storbox.newfragment.argument.FileActionArgs;
import com.jushu.storbox.newfragment.argument.ShareActionArgs;
import com.jushu.storbox.newfragment.argument.TeamListActionArgs;
import com.jushu.storbox.util.PublicTools;
import com.jushu.storbox.view.dialog.PopupMenuWindow;
import com.jushu.storbox.view.resolve.extend.IFileList;

import android.R.integer;
import android.app.Activity;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.ViewGroup.LayoutParams;
import android.view.Window;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.PopupWindow.OnDismissListener;
import android.widget.TextView;
import android.widget.Toast;

public class MainFrameActivity extends Activity implements IFileList {

	FrameLayout titleContainer = null;
	View titleView = null;
	FrameLayout footerContainer = null;
	View actionView = null;
	View vDarkBg = null;

	FooterHolder mFooterHolder = null;

	FragmentManager mFragmentManager = null;

	AbsFrameFragment currentFragment = null;

	ApplicationHolder holder = new ApplicationHolder();

	private Map<Integer, AbsFrameFragment> fragmentMap = new HashMap<Integer, AbsFrameFragment>();

	private int fragmentKey;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.action_main_frame_view);
		mFragmentManager = getFragmentManager();
		titleContainer = (FrameLayout) findViewById(R.id.main_frame_title_fl);
		footerContainer = (FrameLayout) findViewById(R.id.main_frame_footer_fl);
		vDarkBg = findViewById(R.id.vDarkBg);

		mFragmentManager = getFragmentManager();

		// init footer view
		mFooterHolder = new FooterHolder(this);
		setActionView(mFooterHolder.footerView);

		initFragment();
		// init content view: open fileFragment
//		FileActionArgs argument = new FileActionArgs();
//		argument.setFolderId("0");
//		argument.setFolderName(getResources().getString(R.string.my_cloud_drive));
//		argument.setOwnerId(ShareDriveApplication.getInstance().getWnerID());
//		mFooterHolder.fileAction.setSelected(true);
//		openFragment(new FileFragment(), argument);
		
		mFooterHolder.fileAction.setSelected(true);
		switchingContentFragment(R.id.frame_action_file);

		User user = DAOFactory.instance(this).getUserDao().getUser(ShareDriveApplication.getInstance().getWnerID());
		if (user != null && user.getAlbumAutoBackup() == IUserDao.ALBUM_AUTO_BACKUP_TRUE) {
			AlbumUploadTaskManager.instance().startTaskExecuteService();
			AlbumBackManager.instance(this).startAlbumBackup();
		}

		ShareScanManager.getInstance().init(this);
	}

	@Override
	protected void onStart() {
		ShareScanManager.getInstance().startScanShare();
		super.onStart();
	}

	@Override
	protected void onPause() {
		unregisterReceiver(re);
		super.onPause();
	}

	@Override
	protected void onResume() {
		registerBoradcastReceiver();
		super.onResume();
	}

	@Override
	protected void onStop() {
		ShareScanManager.getInstance().stopScanShare();
		super.onStop();
	}

	public void hiddenTitleContainer() {
		titleContainer.setVisibility(View.GONE);
	}

	public void displayTitleContainer() {
		titleContainer.setVisibility(View.VISIBLE);
	}

	public void hiddenFootContainer() {
		footerContainer.setVisibility(View.GONE);
	}

	public void displayFootContainer() {
		footerContainer.setVisibility(View.VISIBLE);
	}

	public void openFragment(AbsFrameFragment fragment, Arguments argument) {
		currentFragment = fragment;
		mFragmentManager = getFragmentManager();
		fragment.setArgument(argument);
		FragmentTransaction transaction = mFragmentManager.beginTransaction();
		transaction.replace(R.id.main_content_container_fl, fragment);
		transaction.commit();
	}

	public void setTitleView(View titleView) {
		if (titleView != null) {
			// replace view in layout
			titleContainer.removeAllViews();
			LayoutParams params = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
			titleContainer.addView(titleView, params);
			this.titleView = titleView;
		}
	}

	public View getTitleView() {
		return titleView;
	}

	public void setActionView(View actionView) {
		if (actionView != null) {
			// replace view in layout
			footerContainer.removeAllViews();
			LayoutParams params = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
			footerContainer.addView(actionView, params);
			this.actionView = actionView;
		}
	}

	public View getActionView() {
		return actionView;
	}

	private PopupMenuWindow morePopupWindow = null;

	public class FooterHolder {
		public View footerView = null;

		HolderGroup fileAction = null;
		HolderGroup shareAction = null;
		HolderGroup teamSpaceAtion = null;
		HolderGroup moreAction = null;

		public View popMenu = null;
		HolderGroup settingAction = null;
		HolderGroup translateAction = null;
		HolderGroup backupAction = null;

		View newShareShip = null;

		public FooterHolder(Context context) {
			footerView = LayoutInflater.from(context).inflate(R.layout.action_frame_bottom_items, footerContainer,
					false);

			fileAction = new HolderGroup(footerView.findViewById(R.id.frame_action_file));
			fileAction.initView(R.id.frame_action_file_im, R.id.frame_action_file_tv);
			fileAction.setOnClickListener(new HolderClickListener() {
				@Override
				public void onClick(View arg0) {
					super.onClick(arg0);
					fileAction.setSelected(true);
//					fragmentKey = arg0.getId();
//					FileFragment fileFragment = (FileFragment) fragmentMap.get(fragmentKey);
//					if (null == fileFragment) {
//						fileFragment = new FileFragment();
//						FileActionArgs argument = new FileActionArgs();
//						argument.setFolderId("0");
//						argument.setFolderName(getResources().getString(R.string.my_cloud_drive));
//						argument.setOwnerId(ShareDriveApplication.getInstance().getWnerID());
//						fileFragment.setArgument(argument);
//						FragmentTransaction transaction = mFragmentManager.beginTransaction();
//						transaction.add(R.id.main_content_container_fl, fileFragment);
//						transaction.commit();
//						fragmentMap.put(arg0.getId(), fileFragment);
//					}
//					 openFragment(new FileFragment(), argument);
					switchingContentFragment(arg0.getId());
				}
			});
			fileAction.setSelectBackgroud(R.mipmap.ic_nav_select_floder, R.mipmap.ic_nav_floder);

			shareAction = new HolderGroup(footerView.findViewById(R.id.frame_action_share));
			shareAction.initView(R.id.frame_action_share_im, R.id.frame_action_share_tv);
			shareAction.setOnClickListener(new HolderClickListener() {
				@Override
				public void onClick(View arg0) {
					super.onClick(arg0);
					shareAction.setSelected(true);
//					ShareActionArgs argument = new ShareActionArgs();
//					openFragment(new ShareFragment(), argument);
					switchingContentFragment(arg0.getId());
				}
			});
			shareAction.setSelectBackgroud(R.mipmap.ic_nav_select_share, R.mipmap.ic_nav_share);

			newShareShip = footerView.findViewById(R.id.have_new_share);

			teamSpaceAtion = new HolderGroup(footerView.findViewById(R.id.frame_action_teamspace));
			teamSpaceAtion.initView(R.id.frame_action_teamspace_im, R.id.frame_action_teamspace_tv);
			teamSpaceAtion.setOnClickListener(new HolderClickListener() {
				@Override
				public void onClick(View arg0) {
					super.onClick(arg0);
					teamSpaceAtion.setSelected(true);
//					TeamListActionArgs argument = new TeamListActionArgs();
//					openFragment(new TeamFragment(), argument);
					switchingContentFragment(arg0.getId());
				}
			});
			teamSpaceAtion.setSelectBackgroud(R.mipmap.ic_nav_select_teamspace, R.mipmap.ic_nav_teamspace);

			moreAction = new HolderGroup(footerView.findViewById(R.id.frame_action_more));
			moreAction.initView(R.id.frame_action_more_im, R.id.frame_action_more_tv);
			moreAction.setOnClickListener(new HolderClickListener() {
				@Override
				public void onClick(View view) {
					super.onClick(view);
					moreAction.setSelected(true);
					if (morePopupWindow == null) {
						morePopupWindow = new PopupMenuWindow(MainFrameActivity.this, LayoutParams.WRAP_CONTENT,
								LayoutParams.WRAP_CONTENT, R.layout.more_popupmenu) {
							protected void onInflaterFinished(View contentView) {
								popMenu = contentView;
								popMenu.setOnTouchListener(new OnTouchListener() {
									@Override
									public boolean onTouch(View view, MotionEvent motionevent) {
										if (morePopupWindow != null && morePopupWindow.isShowing()) {
											morePopupWindow.dismiss();
										}
										return false;
									}
								});

								if (backupAction == null) {
									backupAction = new HolderGroup(contentView.findViewById(R.id.layout_photo_bakup));
									backupAction.initView(R.id.meun_photobakup_im, R.id.meun_photobakup_tv);
									backupAction.setOnClickListener(photoBackListener);
								}

								if (translateAction == null) {
									translateAction = new HolderGroup(contentView.findViewById(R.id.layout_translate));
									translateAction.initView(R.id.meun_translate_im, R.id.meun_translate_tv);
									translateAction.setOnClickListener(translateListener);
								}

								if (settingAction == null) {
									settingAction = new HolderGroup(contentView.findViewById(R.id.layout_setting));
									settingAction.initView(R.id.meun_setting_im, R.id.meun_setting_tv);
									settingAction.setOnClickListener(settingListener);
								}
							}
						};
						morePopupWindow.setOnDismissListener(new OnDismissListener() {
							@Override
							public void onDismiss() {
								vDarkBg.setVisibility(View.GONE);
							}
						});
					}

					// show
					vDarkBg.setVisibility(View.VISIBLE);

					int[] location = new int[2];
					view.getLocationOnScreen(location);

					if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
						morePopupWindow.showAsDropDown(footerView, Gravity.NO_GRAVITY,
								(footerView.getWidth() + morePopupWindow.getWidth()),
                                -location[1] - morePopupWindow.getHeight());
					}else{
						morePopupWindow.showAtLocation(footerView, Gravity.NO_GRAVITY,
								footerView.getWidth() - morePopupWindow.getWidth(),
								location[1] - morePopupWindow.getHeight());
					}

				}
			});
			moreAction.setSelectBackgroud(R.mipmap.ic_nav_select_more, R.mipmap.ic_nav_more);

		}

		OnClickListener photoBackListener = new OnClickListener() {
			public void onClick(View arg0) {
				if (morePopupWindow != null && morePopupWindow.isShowing()) {
					morePopupWindow.dismiss();
				}
//				Arguments argument = new Arguments();
//				openFragment(new AlbumBackFragment(), argument);
				switchingContentFragment(arg0.getId());
			}
		};
		OnClickListener translateListener = new OnClickListener() {
			public void onClick(View arg0) {
				if (morePopupWindow != null && morePopupWindow.isShowing()) {
					morePopupWindow.dismiss();
				}
//				Arguments argument = new Arguments();
//				openFragment(new TranslateFragment(), argument);
				switchingContentFragment(arg0.getId());
			}
		};
		OnClickListener settingListener = new OnClickListener() {
			public void onClick(View arg0) {
				if (morePopupWindow != null && morePopupWindow.isShowing()) {
					morePopupWindow.dismiss();
				}
//				Arguments argument = new Arguments();
//				openFragment(new SettingFragment(), argument);
				switchingContentFragment(arg0.getId());
			}
		};

		class HolderClickListener implements OnClickListener {
			@Override
			public void onClick(View arg0) {
				resetAllAction();
			}

			private void resetAllAction() {
				fileAction.setSelected(false);
				shareAction.setSelected(false);
				teamSpaceAtion.setSelected(false);
				moreAction.setSelected(false);
			}
		}

	}

	protected class HolderGroup {
		ImageView imageView;
		TextView textView;
		View viewGroup;
		int selectBackgroud = 0;
		int unSelectBackgroud = 0;
		int textSelectedColor = 0xff1a76c3;
		int textUnSelectedColor = 0xff959595;

		OnClickListener groupClickListener = null;

		HolderGroup(View group) {
			viewGroup = group;
		}

		public void initView(int imageResId, int textResId) {
			if (viewGroup == null) {
				return;
			}
			imageView = (ImageView) viewGroup.findViewById(imageResId);
			textView = (TextView) viewGroup.findViewById(textResId);
		}

		public void setOnClickListener(OnClickListener l) {
			if (viewGroup != null) {
				viewGroup.setOnClickListener(l);
			}
		}

		public void setSelected(boolean selected) {
			imageView.setSelected(selected);
			if (selected) {
				textView.setTextColor(textSelectedColor);
				if (selectBackgroud > 0) {
					imageView.setImageResource(selectBackgroud);
				}
			} else {
				textView.setTextColor(textUnSelectedColor);
				if (selectBackgroud > 0) {
					imageView.setImageResource(unSelectBackgroud);
				}
			}
		}

		public void setSelectBackgroud(int selectBackgroud, int unSelectBackgroud) {
			this.selectBackgroud = selectBackgroud;
			this.unSelectBackgroud = unSelectBackgroud;
		}
	}

	public AbsFrameFragment getCurrentFragment() {
		return currentFragment;
	}

	@Override
	public void onBackPressed() {
		if (getCurrentFragment() instanceof FileFragment && ((FileFragment) getCurrentFragment()).isMultiSelectFlag()) {
			((FileFragment) getCurrentFragment()).new TitleViewHolder().cancelMultiSelect();
		} else {
			if (currentFragment != null) {
				if (!currentFragment.handleBackPressed()) {
					long currentMillis = System.currentTimeMillis();
					if ((currentMillis - holder.getLastExitTime()) < ApplicationHolder.EXIT_SPACE_TIME_MILLIS) {
						// new BaseAction().logout(MainFrameActivity.this);
						super.onBackPressed();
					} else {
						holder.setLastExitTime(currentMillis);
						Toast.makeText(this, R.string.main_fragment, Toast.LENGTH_SHORT).show();
					}
				}
			}
		}
	}

	@Override
	public void updateCurrentFolder(String ownerId, String folderId, String folderName) {
		currentFragment.updateCurrentFolder(ownerId, folderId, folderName);

	}

	@Override
	public void updateSelectAll(boolean selectState) {
		currentFragment.updateSelectAll(selectState);
	}
	
	@Override
	protected void onSaveInstanceState(Bundle outState) {
		// TODO Auto-generated method stub
//		super.onSaveInstanceState(outState);
	}

	/**
	 * Decide whether the group update view should be show
	 * 
	 * @param groupId
	 *            {@link UiConstant#UPDATE_GROUP_BASE}+
	 * @param show
	 */
	private void updateGroupUpdateVisiable(int groupId, boolean show) {
		switch (groupId) {
		case UiConstant.UPDATE_GROUP_FILE:
			break;
		case UiConstant.UPDATE_GROUP_SHARE:
			if (mFooterHolder.newShareShip != null) {
				if (show) {
					mFooterHolder.newShareShip.setVisibility(View.VISIBLE);
				} else {
					mFooterHolder.newShareShip.setVisibility(View.GONE);
				}
			}
			break;
		case UiConstant.UPDATE_GROUP_TEAM:
			break;
		case UiConstant.UPDATE_GROUP_MORE:
			break;
		}
	}

	private class ApplicationHolder {
		/** the space of exit time */
		public static final int EXIT_SPACE_TIME_MILLIS = 1000;

		public ApplicationHolder() {
			lastExitTime = System.currentTimeMillis();
		}

		private long lastExitTime = 0;

		public long getLastExitTime() {
			return lastExitTime;
		}

		public void setLastExitTime(long lastExitTime) {
			this.lastExitTime = lastExitTime;
		}
	}

	/**
	 * 初始化Fragment，并存入Map
	 */
	private void initFragment() {
		FileFragment fileFragment = new FileFragment();
		ShareFragment shareFragment = new ShareFragment();
		TeamFragment teamFragment = new TeamFragment();
		AlbumBackFragment albumBackFragment = new AlbumBackFragment();
		TranslateFragment translateFragment = new TranslateFragment();
		SettingFragment settingFragment = new SettingFragment();

		FileActionArgs fileArgument = new FileActionArgs();
		fileArgument.setFolderId("0");
		fileArgument.setFolderName(getResources().getString(R.string.my_cloud_drive));
		fileArgument.setOwnerId(ShareDriveApplication.getInstance().getWnerID());
		fileFragment.setArgument(fileArgument);

		ShareActionArgs shareArgument = new ShareActionArgs();
		shareFragment.setArgument(shareArgument);

		TeamListActionArgs teamListArgument = new TeamListActionArgs();
		teamFragment.setArgument(teamListArgument);

		fragmentMap.put(R.id.frame_action_file, fileFragment);
		fragmentMap.put(R.id.frame_action_share, shareFragment);
		fragmentMap.put(R.id.frame_action_teamspace, teamFragment);
		fragmentMap.put(R.id.layout_photo_bakup, albumBackFragment);
		fragmentMap.put(R.id.layout_translate, translateFragment);
		fragmentMap.put(R.id.layout_setting, settingFragment);
	}

	/**
	 * 切换fragment
	 * 
	 * @param key
	 */
	private void switchingContentFragment(int key) {

		AbsFrameFragment showFragment = fragmentMap.get(key);
		FragmentTransaction transaction = mFragmentManager.beginTransaction();
		if (fragmentKey != 0) {
			AbsFrameFragment hideFragment = fragmentMap.get(fragmentKey);
			transaction.hide(hideFragment);
		}
		if (showFragment.isAdded()) {
			transaction.show(showFragment);
			showFragment.setTitleView();
		}else {
			transaction.add(R.id.main_content_container_fl, showFragment);
		}
		transaction.commit();
		currentFragment = showFragment;
		fragmentKey = key;
	}

	BroadcastReceiver re = new BroadcastReceiver() {

		@Override
		public void onReceive(Context context, Intent intent) {
			String action = intent.getAction();
			if (action.equals(ReceiverConstent.DOWNLOAD_CATCH_NOT_ENOUGH)) {
				Toast toast = Toast.makeText(context, R.string.no_enough_space, Toast.LENGTH_SHORT);
				toast.setGravity(Gravity.CENTER, 0, 0);
				toast.show();
			} else if (ReceiverConstent.NEW_SHARE_SHIP_FIND.equals(action)) {
				updateGroupUpdateVisiable(UiConstant.UPDATE_GROUP_SHARE, true);
			} else if (ReceiverConstent.NO_NEW_SHARE_SHIP_FIND.equals(action)) {
				updateGroupUpdateVisiable(UiConstant.UPDATE_GROUP_SHARE, false);
			}
		}
	};

	public void registerBoradcastReceiver() {
		IntentFilter myIntentFilter = new IntentFilter();
		myIntentFilter.addAction(ReceiverConstent.DOWNLOAD_CATCH_NOT_ENOUGH);
		myIntentFilter.addAction(ReceiverConstent.NEW_SHARE_SHIP_FIND);
		myIntentFilter.addAction(ReceiverConstent.NO_NEW_SHARE_SHIP_FIND);
		// 注册广播
		registerReceiver(re, myIntentFilter);
	}

}
